import React, { useState, useEffect, useRef } from "react";
import { CaretLeftOutlined, CaretRightOutlined } from "@ant-design/icons";
import type { typesitem } from "@/api/Home/type";

interface ScrollTypeSelectorProps {
  typesList: typesitem[];
  selectedType: string;
  onTypeChange?: (item: typesitem) => void;
  colorPairs?: { background: string; primary: string }[];
  showCount?: boolean;
}

const DEFAULT_COLOR_PAIRS = [
  { background: "#d3f4f4", primary: "#119c9c" },
  { background: "#ccf3ff", primary: "#008faa" },
  { background: "#c8f1f1", primary: "#00a6a8" },
  { background: "#d0ecff", primary: "#2a9df4" },
  { background: "#e0f0ff", primary: "#3f8df3" },
  { background: "#e0eaff", primary: "#4e6eff" },
  { background: "#e8e4ff", primary: "#6a5bff" },
  { background: "#e8f3ff", primary: "#3387d4" },
  { background: "#e4f8ff", primary: "#2aa7cc" },
  { background: "#d6faff", primary: "#00b7c6" },
  { background: "#daf5ff", primary: "#009ac9" },
  { background: "#cfeeff", primary: "#3ca0e0" },
  { background: "#dbeaff", primary: "#577efc" },
  { background: "#e7e9ff", primary: "#636fef" },
  { background: "#dee9ff", primary: "#567fe9" },
];

const ScrollTypeSelector: React.FC<ScrollTypeSelectorProps> = ({
  typesList,
  onTypeChange,
  selectedType,
  colorPairs = DEFAULT_COLOR_PAIRS,
  showCount = true,
}) => {
  const containerRef = useRef<HTMLDivElement>(null);

  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);

  const updateScrollStatus = () => {
    if (!containerRef.current) return;

    const { scrollLeft, scrollWidth, clientWidth } = containerRef.current;
    setCanScrollLeft(scrollLeft > 0);
    setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 1);
  };

  useEffect(() => {
    updateScrollStatus();

    const el = containerRef.current;
    if (!el) return;

    el.addEventListener("scroll", updateScrollStatus);
    window.addEventListener("resize", updateScrollStatus);

    return () => {
      el.removeEventListener("scroll", updateScrollStatus);
      window.removeEventListener("resize", updateScrollStatus);
    };
  }, [typesList]);

  const CARD_WIDTH = 140;

  const handleScrollLeft = () => {
    containerRef.current?.scrollBy({ left: -CARD_WIDTH, behavior: "smooth" });
  };

  const handleScrollRight = () => {
    containerRef.current?.scrollBy({ left: CARD_WIDTH, behavior: "smooth" });
  };

  const handleTypeClick = (item: typesitem) => {
    if (item.name !== selectedType) onTypeChange?.(item);
  };

  return (
    <div className="flex justify-between w-full items-center mb-2.5">
      {canScrollLeft && (
        <div
          className="cursor-pointer h-14 select-none flex items-center justify-center mb-4 hover:bg-gray-200 rounded"
          onClick={handleScrollLeft}
          role="button"
          aria-label="向左滚动"
          tabIndex={0}
          onKeyDown={(e) => e.key === "Enter" && handleScrollLeft()}
        >
          <CaretLeftOutlined style={{ fontSize: 20 }} />
        </div>
      )}

      <div
        ref={containerRef}
        className="flex flex-1 items-center overflow-x-auto scrollbar-hidden whitespace-nowrap"
      >
        {typesList.map((item, index) => {
          const colors = colorPairs[index % colorPairs.length];
          const isSelected = selectedType === item.name;

          return (
            <div
              key={item.name}
              onClick={() => handleTypeClick(item)}
              className={`h-14 min-w-35 relative flex items-center mr-4 mb-4 pl-4 pr-4 pt-2 pb-2 text-4 rounded-[10px] cursor-pointer transition-all duration-200 ${
                isSelected ? "shadow-md" : ""
              }`}
              style={{
                backgroundColor: colors.background,
                justifyContent: showCount === false ? "center" : "flex-start",
              }}
            >
              <div className="max-w-[100px] truncate">{item.name}</div>

              {showCount && (
                <div
                  className="rounded-[18px] text-white text-center ml-4 pl-2 pr-2 pt-1 pb-1 min-w-[80px]"
                  style={{ backgroundColor: colors.primary }}
                >
                  {item.active}/{item.total}
                </div>
              )}

              {isSelected && (
                <div
                  className="absolute left-1/2 -translate-x-1/2 bottom-[-17px] w-0 h-0"
                  style={{
                    borderLeft: "10px solid transparent",
                    borderRight: "10px solid transparent",
                    borderTop: `17.32px solid ${colors.background}`,
                  }}
                />
              )}
            </div>
          );
        })}
      </div>

      {canScrollRight && (
        <div
          className="cursor-pointer h-14 select-none flex items-center justify-center mb-4 hover:bg-gray-200 rounded"
          onClick={handleScrollRight}
          role="button"
          aria-label="向右滚动"
          tabIndex={0}
          onKeyDown={(e) => e.key === "Enter" && handleScrollRight()}
        >
          <CaretRightOutlined style={{ fontSize: 20 }} />
        </div>
      )}
    </div>
  );
};

export default ScrollTypeSelector;
